import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { RegisterInfo } from './register-company.component';

@Injectable()
export class RegisterCompanyService {

    constructor(private _http: Http) { }

    save(url, registerInfo: RegisterInfo): Promise<any> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        const body = new URLSearchParams();
        Object.keys(registerInfo).forEach(key => {
          body.set(key, registerInfo[key]);
        });

         return this._http.get(url+"?"+body.toString()).toPromise()
                    .then(this.extractData)
                    .catch(this.handleError);
    }

    extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    handleError(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            if (error.status > 200) {
                errMsg = '网络异常';
            } else {
                errMsg = '网络异常';
            }
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Promise.reject(errMsg);
    }
}
